<?php

/**
 * 加解密
 * @author WangLei
 * Time: 下午2:48 16-11-30
 */
class LibDencrypt
{
    private $hex_iv = '00000000000000000000000000000000'; # converted JAVA byte code in to HEX and placed it here
    private $key = 'J2z0W1x7.IYueDan'; #Same as in JAVA
    const KEY = 'J2z0Wx7.';
    const KEY_UFO = 'qcQ7SVfWaUEvIrqR';

    function __construct($key = self::KEY)
    {
        $this->key = $key;
        $this->key = hash('sha256', $this->key, true);
        echo $this->key.'<br/>';
    }

    //新的DES加密算法
    public function decrypt($str, $decode = 1)
    {
        $key = $this->key;
        $algo = 'des-ecb'; //'aes-256-cbc'
        $option = 0; //OPENSSL_RAW_DATA
        return ($decode ? 'openssl_decrypt' : 'openssl_encrypt')($str, $algo, $key, OPENSSL_RAW_DATA);
        // $str = base64_decode($str);
    }

    /*
      For PKCS7 padding
     */
    private function addpadding($string, $blocksize = 16)
    {
        $len = strlen($string);
        $pad = $blocksize - ($len % $blocksize);
        $string .= str_repeat(chr($pad), $pad);
        return $string;
    }

    private function strippadding($string)
    {
        $slast = ord(substr($string, -1));
        $slastc = chr($slast);
        $pcheck = substr($string, -$slast);
        if (@preg_match("/$slastc{" . $slast . "}/", $string)) {
            $string = substr($string, 0, strlen($string) - $slast);
            return $string;
        } else {
            return false;
        }
    }

    function hexToStr($hex)
    {
        $string = '';
        for ($i = 0; $i < strlen($hex) - 1; $i += 2) {
            $string .= chr(hexdec($hex[$i] . $hex[$i + 1]));
        }
        return $string;
    }

     /**
     * 简单加密
     * @param string $pwd
     * @return string
     */
    static function _crypt($str)
    {
        return md5('.!#$%' . $str . '!$#@#$@');
    }
}
